package com.huisu.netty.chatserver;

import com.alibaba.fastjson2.JSON;
import com.huisu.netty.enums.Command;
import com.huisu.netty.pojo.ChatModel;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private final static Map<Long, Channel> privateChannel = new ConcurrentHashMap<>();
    private final static ChannelGroup channelGroups = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        channelGroups.add(ctx.channel());
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        ctx.channel().writeAndFlush(new TextWebSocketFrame(format.format(new Date()) + " 欢迎你的上线"));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        channelGroups.remove(ctx.channel());
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        channelGroups.remove(ctx.channel());
        ctx.close();
    }


    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        ChatModel chatModel = JSON.parseObject(textWebSocketFrame.text(),ChatModel.class);
        switch(Command.match(chatModel.getTypeCode())) {
            case OFFLINE:
                privateChannel.remove(chatModel.getUserKey());
                channelGroups.remove(channelHandlerContext.channel());
                break;
            case CONNECT:
                privateChannel.put(chatModel.getUserKey(),channelHandlerContext.channel());
                break;
            case PRIVATE:
                Channel channel = privateChannel.get(chatModel.getTarget());
                if (channel != null && channel.isActive()) {
                    chatModel.setType(0);
                    chatModel.setSendTime(new Date());
                    channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(chatModel)));
                }else {
                    channelHandlerContext.writeAndFlush(new TextWebSocketFrame("好友不在线，请等会在发送数据吧"));
                }
                break;
            case RADIO:
                for (Map.Entry<Long, Channel> channelEntry : privateChannel.entrySet()) {
                    chatModel.setType(3);
                    chatModel.setSendTime(new Date());
                    if ( channelEntry.getValue() != channelHandlerContext.channel()) {
                        channelEntry.getValue().writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(chatModel)));
                    }
                }
                break;
            case LINERADIO:
                chatModel.setType(3);
                chatModel.setSendTime(new Date());
                channelGroups.forEach( item -> {
                    if( item != channelHandlerContext.channel() ) {
                        item.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(chatModel)));
                    }
                });
                break;
         }
    }
}
